import pyaudio
import ffmpeg
import subprocess
from multiprocessing import Queue, Process, Event


audioDecodeInput = ffmpeg.input(filename="plughw:2,0", format="alsa")
audioDecode = audioDecodeInput.audio
audioDecodeStream = ffmpeg.output(audioDecode, filename='pipe:', format='wav', ac='2', ar='48000')
audioDecodeProcess: subprocess.Popen = audioDecodeStream.run_async(pipe_stdout=True)

audioOutProcess = subprocess.Popen("aplay -", stdin=subprocess.PIPE, shell=True)


def audioPutThread(in_DecodeBuffer, in_END_EVENT):
    while not in_END_EVENT.is_set():
        try:
            print("开始读取")
            res = audioDecodeProcess.stdout.read(1024)
            print("推送中")
            in_DecodeBuffer.put(res)
        except KeyboardInterrupt:
            break
    in_END_EVENT.set()


def audioOutThread(in_DecodeBuffer, in_END_EVENT):
    while not in_END_EVENT.is_set():
        try:
            print("准备写入")
            res = in_DecodeBuffer.get()
            print("写入中")
            audioOutProcess.stdin.write(res)
        except KeyboardInterrupt:
            break
    in_END_EVENT.set()


if __name__ == '__main__':
    DecodeBuffer = Queue(100)
    event = Event()
    # proc1 = Thread(target=audioEncodeThread)
    # proc1.setDaemon(True)
    proc3 = Process(target=audioPutThread, args=(DecodeBuffer, event), daemon=True)
    proc4 = Process(target=audioOutThread, args=(DecodeBuffer, event), daemon=True)

    proc3.start()
    proc4.start()

    proc3.join()
    proc4.join()